package com.tz.online.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;

/****
 * 此类是模拟省份、地区、市县、乡镇 四级地址的一个工具类
 * @author yejf
 *
 */
public class AddressUtil {
	
	private static List<Province> all;
	private static String path = "address.json";
	
	/****
	 * 利用静态代码块来读取 address.json 文件，并它把解析成java对象
	 */
	static {
		InputStream in = AddressUtil.class.getResourceAsStream(path);
		//创建字符数组输入流
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
			//
			StringBuilder builder = new StringBuilder();
			String line = null;
			while((line = reader.readLine()) != null) {
				builder.append(line);
			}
//			System.out.println(builder.toString());
			//再把此builder中的内容解析成java对象
			all = JSON.parseArray(builder.toString(), Province.class);
			//
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(reader != null)
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		
	}
	
	/*****
	 * 获取所有的省份信息
	 * @return
	 */
	public static List<Province> getProvinces(){
		List<Province> provinces = new ArrayList<>();
		//遍历所有的all数据，只取出省份
		for(Province p : all) {
			Province justProvince = new Province(p.getId(), p.getName());
			provinces.add(justProvince);
		}
		return provinces;
	}
	
	/******
	 * 根据省份名 来查询出  city
	 * @param province
	 * @return
	 */
	public static List<City> getCityByProvince(String province) {
		//遍历整个集合
		for(Province p : all) {
			//判断
			if(province.equals(p.getName())) {
				return p.getCity();
			}
		}
		return null;
	}
	
	/******
	 * 根据province和city 来查询出 area
	 * @param province
	 * @param area
	 * @return
	 */
	public static List<String> getAreaByCity(String province, String city) {
		//遍历整个集合
		for(Province p : all) {
			//判断
			if(province.equals(p.getName())) {
				// 进一步遍历 city
				for(City c : p.getCity()) {
					// 判断
					if(city.equals(c.getName())) {
						return c.getArea();
					}
				}
			}
		}
		return null;
	}
	
	
	public static void main(String[] args) {
		List<Province> plist = getProvinces();
		for(Province p : plist) {
			System.out.println(p);
		}
		
		//测试根据省份来获取city
		/*List<City> pcity = getCityByProvince("江西");
		if(pcity != null) {
			for(City c : pcity) {
				System.out.println(c);
			}
		} else {
			System.out.println("无记录");
		}*/
		
		//
		List<String> parea = getAreaByCity("江苏", "苏州");
		if(parea != null) {
			for(String a : parea) {
				System.out.println(a);
			}
		}
	}
}
